<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>设备状态管理</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="refreshData"
              :loading="loading">
              刷新
            </el-button>
          </div>



          <el-table
            :data="deviceList"
            v-loading="loading"
            style="width: 100%;height: 200px"
            @sort-change="sortChange">

            <el-table-column prop="deviceId" label="设备ID" sortable="custom" min-width="150"></el-table-column>
            <el-table-column prop="status" label="状态" width="100" sortable="custom">
              <template slot-scope="scope" >
                <el-tag :type="scope.row.status ? 'success' : 'danger'">
                  {{ scope.row.status ? '在线' : '离线' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastActive" label="最后活动时间" width="180" sortable="custom">
              <template slot-scope="scope">
                {{parseTime(scope.row.lastActive)}}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleControl(scope.row)"
                  :disabled="!scope.row.status">
                  控制
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleRemove(scope.row)">
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="listQuery.page"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="listQuery.limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>设备统计信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <div class="stat-item">
                <div class="stat-label">总设备数</div>
                <div class="stat-value">{{ statistics.total || 0 }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <div class="stat-item">
                <div class="stat-label">在线设备</div>
                <div class="stat-value online">{{ statistics.online || 0 }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <div class="stat-item">
                <div class="stat-label">离线设备</div>
                <div class="stat-value offline">{{ statistics.offline || 0 }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <div class="stat-item">
                <div class="stat-label">在线率</div>
                <div class="stat-value rate">
                  {{ statistics.onlineRate ? (statistics.onlineRate * 100).toFixed(2) + '%' : '0%' }}
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 控制对话框 -->
    <el-dialog :title="'控制设备: ' + currentDevice" :visible.sync="controlDialogVisible" width="40%">
      <el-form :model="controlForm" label-width="100px">
        <el-form-item label="控制命令">
          <el-input
            v-model="controlForm.command"
            type="textarea"
            :rows="4"
            placeholder="请输入控制命令">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="controlDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sendCommand">发送</el-button>
      </span>
    </el-dialog>

    <!-- 移除确认对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="removeDialogVisible"
      width="30%">
      <span>确定要移除设备 "{{ currentDevice }}" 吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="removeDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmRemove">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import {
  getDeviceStatusList,
  getDeviceStatistics,
  removeDevice,
  sendDeviceCommand
} from '@/api/smart/device'

export default {
  name: 'DeviceStatus',
  data() {
    return {
      deviceList: [],
      statistics: {},
      loading: false,
      listQuery: {
        page: 1,
        limit: 20,
        sort: null,
        order: null
      },
      total: 0,
      controlDialogVisible: false,
      removeDialogVisible: false,
      currentDevice: '',
      controlForm: {
        command: ''
      }
    }
  },
  created() {
    this.getList()
    this.getStatistics()
  },
  methods: {
    getList() {
      this.loading = true
      getDeviceStatusList().then(response => {
        console.log( "----------",response.data)
        this.deviceList = Object.keys(response.data).map(deviceId => ({
          deviceId,
          status: response.data[deviceId],
          lastActive: Date.now() // 这里应该从后端获取实际最后活动时间
        }))
        console.log( "----------", this.deviceList)
        this.total = this.deviceList.length
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    getStatistics() {
      getDeviceStatistics().then(response => {
        this.statistics = response.data
      })
    },

    refreshData() {
      this.getList()
      this.getStatistics()
      this.$message.success('数据已刷新')
    },

    handleControl(device) {
      this.currentDevice = device.deviceId
      this.controlForm.command = ''
      this.controlDialogVisible = true
    },

    sendCommand() {
      if (!this.controlForm.command) {
        this.$message.warning('请输入控制命令')
        return
      }

      sendDeviceCommand(this.currentDevice, this.controlForm.command).then(() => {
        this.$message.success('命令已发送')
        this.controlDialogVisible = false
      })
    },

    handleRemove(device) {
      this.currentDevice = device.deviceId
      this.removeDialogVisible = true
    },

    confirmRemove() {
      removeDevice(this.currentDevice).then(() => {
        this.$message.success('设备已移除')
        this.removeDialogVisible = false
        this.getList()
        this.getStatistics()
      })
    },

    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },

    sortChange(column) {
      if (column.prop && column.order) {
        this.listQuery.sort = column.prop
        this.listQuery.order = column.order === 'ascending' ? 'asc' : 'desc'
      } else {
        this.listQuery.sort = null
        this.listQuery.order = null
      }
      this.getList()
    }
  }
}
</script>

<style scoped>
.stat-item {
  text-align: center;
  padding: 15px 0;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.stat-value.online {
  color: #67C23A;
}

.stat-value.offline {
  color: #F56C6C;
}

.stat-value.rate {
  color: #E6A23C;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
